package case28

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"net/http"
	"time"
)

func Test() {

	fmt.Println("🎯示例二十八：自定义验证器-复杂业务验证器")

	router := gin.Default()

	// 注册自定义验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("futureDate", futureDateValidator)
		v.RegisterValidation("discount", discountValidator)
	}

	router.POST("/order", func(c *gin.Context) {
		var req CreateOrderRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "订单创建成功",
			"data":    req,
		})
	})

	router.Run(":60000")

}

// 订单创建请求
type CreateOrderRequest struct {
	ProductID  string    `json:"product_id" binding:"required"`
	Quantity   int       `json:"quantity" binding:"required,min=1,max=10"`
	OrderDate  time.Time `json:"order_date" binding:"required,futureDate"`
	CustomerID string    `json:"customer_id" binding:"required"`
	Discount   float64   `json:"discount" binding:"discount"`
}

// 未来日期验证器
var futureDateValidator validator.Func = func(fl validator.FieldLevel) bool {
	date, ok := fl.Field().Interface().(time.Time)
	if !ok {
		return false
	}
	return date.After(time.Now())
}

// 折扣验证器
var discountValidator validator.Func = func(fl validator.FieldLevel) bool {
	discount, ok := fl.Field().Interface().(float64)
	if !ok {
		return false
	}
	return discount >= 0 && discount <= 1.0 // 折扣在 0-1 之间
}
